import api from "../../api/index.js";
import cache from "../../utils/cache.js";

Page({
  data: {
    currentCompany: {},
    location: {},
    payOrder: {},
    curAddressData: {},
    shippingCarBill: {},
    peisongType: '', // 配送方式 kd,zq 分别表示快递/到店自取
    submitLoding: false,
    remark: '',
    currentDate: new Date().getHours() + ':' + (new Date().getMinutes() % 10 === 0 ? new Date().getMinutes() : Math.ceil(new Date().getMinutes() / 10) * 10),
    minHour: new Date().getHours(),
    minMinute: new Date().getMinutes(),
    // 优惠券相关
    selectCouponShow: false,
    activeCouponIndex: 0,
    toBeSelectedCoupons: [], //待选优惠券
    beSelectedCoupons: [], //已选优惠券
    // 配送费
    freightCharges: {},
    // 用户信息
    user: {},
    mobile: '',
    // 支付相关
    paymentShow: false,
    // 时间选择器
    diningTimeShow: false,
    diningTime: '',
    formatter(type, value) {
      if (type === 'hour') {
        return `${value}点`;
      } else if (type === 'minute') {
        return `${value}分`;
      }
      return value;
    },
    filter(type, options) {
      if (type === 'minute') {
        return options.filter((option) => option % 10 === 0);
      }
      return options;
    }
  },

  onLoad(e) {
    getApp().initLanguage(this);
    wx.setNavigationBarTitle({
      title: "支付确认",
    });
    const user = wx.getStorageSync('user');
    const currentCompany = wx.getStorageSync('currentCompany');
    const peisongType = wx.getStorageSync('peisongType');
    
    cache.getLocation().then((res) => {
      this.setData({
        peisongType,
        currentCompany,
        user,
        location: res
      });
    });
    this.getCouponList();
  },

  onShow() {
    api.getAppConfig({
      method: "POST",
      data: { id: 1 },
    }).then((res) => {
      this.setData({ shopInfo: res.data });
    });

    let peisongType = wx.getStorageSync('peisongType');
    if (!peisongType) {
      peisongType = 'zq'; // 默认自取
    }
    
    let currentAddress = wx.getStorageSync('currentAddress');
    if (currentAddress) {
      this.setData({
        peisongType,
        curAddressData: currentAddress
      });
    }

    this.doneShow();
  },

  doneShow() {
    api.shoppingCartBill({
      method: "POST",
      data: {},
    }).then((res) => {
      this.setData({ shippingCarBill: res.data });
      return res.data;
    }).then(res => {
      const distance = this.data.currentCompany.distance;
      const shoppingCardIds = res.listShoppingCart.map(obj => obj.id);
      api.calculateMoney({
        data: {
          distance,
          shoppingCardIds
        }
      }).then(res => {
        this.setData({ freightCharges: res.data });
      });
    });
  },

  // 配送方式选择
  selected(e) {
    const peisongType = e.currentTarget.dataset.pstype;
    this.setData({ peisongType });
    wx.setStorageSync('peisongType', peisongType);
  },

  // 备注
  remarkChange(e) {
    this.setData({ remark: e.detail.value });
  },

  // 创建订单前置检查
  goCreateOrderPre() {
    if (!this.data.peisongType) {
      wx.showToast({
        title: '请选择用餐方式',
        icon: 'error',
        duration: 2500
      });
      return;
    }
    
    if (this.data.peisongType == 'kd' && !this.data.curAddressData.id) {
      wx.showToast({
        title: '请选择配送地址',
        icon: 'error',
        duration: 2500
      });
      return;
    }

    const _this = this;
    wx.requestSubscribeMessage({
      tmplIds: ['T-BS-ALr_FLajBkItcxuxc5Pty8cIhqKgafVqQbHlts', 'jzknQgpBxe65Jb7l1oZmCR-SGzTaiWI6mOwnyQXQOwM'],
      success(res) {
        _this.goCreateOrder();
      },
      fail(errMsg) {
        _this.goCreateOrder();
      }
    });
  },

  // 创建订单
  goCreateOrder() {
    if (this.data.submitLoding) return;
    
    this.setData({ submitLoding: true });
    let couponRelIds = this.data.beSelectedCoupons.map(i => i.id);
    
    api.orderAddByShoppingCar({
      data: {
        originalMoney: this.data.shippingCarBill.sumMoney,
        receivableMoney: this.data.shippingCarBill.sumMoney,
        deliveryMoney: 3, //配送费用
        deliveryType: this.data.peisongType == 'zq' ? 1 : 2,
        shoppingCartIds: this.data.shippingCarBill.listShoppingCart.map(i => i.id),
        couponRelIds,
        companyId: this.data.currentCompany.id,
        remark: this.data.remark,
        deliveryOrder: {
          userAddressId: this.data.curAddressData.id,
          deliveryType: this.data.peisongType == 'zq' ? 1 : 2,
          userName: this.data.curAddressData.receiver,
          userPhone: this.data.curAddressData.mobile,
          deliveryAddress: this.data.curAddressData.address,
          deliveryAddressTitle: this.data.curAddressData.addressName,
          deliveryAddressLatitude: this.data.curAddressData.latitude,
          deliveryAddressLongitude: this.data.curAddressData.longitude,
        }
      },
    }).then((res) => {
      const payOrder = res.data;
      this.setData({
        paymentShow: true,
        payOrder
      });
    });
  },

  // 重新支付
  payAgain() {
    const payOrder = this.data.payOrder;
    this.setData({
      paymentShow: true,
      payOrder
    });
  },

  // 支付成功回调
  paymentOk(e) {
    this.setData({ paymentShow: false });
    wx.redirectTo({ url: '/pages/all-orders/index' });
  },

  // 支付取消回调
  paymentCancel() {
    this.setData({
      paymentShow: false,
      submitLoding: false
    });
  },

  // 地址相关
  addAddress() {
    wx.navigateTo({ url: "/pages/address/index?modalType=2" });
  },

  selectAddress() {
    wx.navigateTo({ url: "/pages/address/index?modalType=2" });
  },

  // 获取手机号
  async getPhoneNumber(e) {
    if (!e.detail.errMsg || e.detail.errMsg != "getPhoneNumber:ok") {
      wx.showToast({ title: e.detail.errMsg, icon: 'none' });
      return;
    }
    // 这里需要实现获取手机号的逻辑
    // const res = await WXAPI.bindMobileWxapp(...)
    // 实际实现需要根据业务需求
  },

  // 时间选择相关
  diningTimeShow() {
    this.setData({ diningTimeShow: true });
  },

  diningTimeHide() {
    this.setData({ diningTimeShow: false });
  },

  diningTimeConfirm(e) {
    this.setData({ diningTime: e.detail });
    this.diningTimeHide();
  },

  diningTimeChange(a) {
    const selectedHour = a.detail.getColumnValue(0).replace('点', '') * 1;
    if (selectedHour == new Date().getHours()) {
      let minMinute = new Date().getMinutes();
      if (minMinute % 10 !== 0) {
        minMinute = minMinute / 10 + 1;
      }
      this.setData({ minMinute });
    } else {
      this.setData({ minMinute: 0 });
    }
  },

  // 优惠券相关
  getCouponList() {
    api.couponList({
      method: "POST",
      data: { couponStatus: "B" },
    }).then((res) => {
      this.setData({ toBeSelectedCoupons: res.data });
    });
  },

  tabCouponClick(e) {
    this.setData({ activeCouponIndex: e.detail.index });
  },

  selectCoupon() {
    this.setData({ selectCouponShow: !this.data.selectCouponShow });
  },

  selectCouponClose() {
    this.setData({ selectCouponShow: false });
  },

  onToBeCouponTap(e) {
    const { coupon } = e.detail;
    if (coupon) {
      let toBeSelectedCoupons = this.data.toBeSelectedCoupons.filter(obj => obj.id !== coupon.id);
      this.setData({ toBeSelectedCoupons });
      this.data.beSelectedCoupons.push(coupon);
    }
  },

  onBeCouponTap(e) {
    const { coupon } = e.detail;
    if (coupon) {
      let beSelectedCoupons = this.data.beSelectedCoupons.filter(obj => obj.id !== coupon.id);
      this.setData({ beSelectedCoupons });
      this.data.toBeSelectedCoupons.push(coupon);
    }
  }
});